<template>
  <div class="page-list-live">
    <PageList>
      <template #header>工点信息</template>
      <template #filter>
        <el-form
          ref="RefForm"
          :model="formData"
          label-width="auto"
          :validate-on-rule-change="false"
          :rules="formRules"
          :inline="true"
          status-icon
        >
          <div>
            <el-form-item label="工点名称" prop="name">
              <el-input v-model="formData.name" maxlength="13" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="formData.longitude" maxlength="20" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="formData.latitude" maxlength="20" show-word-limit></el-input>
            </el-form-item>
            <el-form-item class="info">坐标请从 http://api.map.baidu.com/lbsapi/getpoint/ 拾取</el-form-item>
          </div>
          <el-form-item label="添加施工示意图">
            <div style="margin-bottom: 10px">
              <el-radio-group v-model="formData.templateName">
                <el-radio label="单洞"></el-radio>
                <el-radio label="双洞"></el-radio>
              </el-radio-group>
            </div>
            <div style="display: flex">
              <el-upload
                ref="imgRef"
                class="upload-demo"
                :headers="{
                  Authorization: `Bearer ${$store.getters.token}`
                }"
                :action="httpUrl"
                multiple
                :limit="1"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false"
              >
                <el-button size="mini" type="primary">自定义</el-button>
              </el-upload>
              <span style="color: #999; margin-left: 10px">(图片只能是 JPG 格式,建议宽高：1200 * 617)</span>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #tab>
        <div class="dialog-footer">
          <el-button :loading="loadingSubmit" type="primary" @click="handleSubmit">确 定</el-button>
        </div>
        <div class="imgBox">
          <!-- <el-button v-if="!formData.useTemplate" class="btnClass" icon="el-icon-delete" style="color: red;" type="text">删除施工示意图</el-button> -->
          <img v-if="imgSrc" :src="imgSrc" alt />
        </div>
      </template>
    </PageList>
  </div>
</template>
<script>
import { assetsImages } from '@/utils/images.js'
import listMixin from '@/mixins/list'
import { eleValidator } from '@/utils/tools'
import { tunnel } from '@/api/api'
import { localhostUrl } from '@/utils/setUrl.js'
export default {
  mixins: [listMixin],
  data() {
    return {
      // 是否存在工点信息，不存在则需要新增，存在则编辑
      isExist: false,
      // 施工示意图
      imgUrl: localhostUrl + '/',
      imgSrc: '',
      // 获取图片地址
      httpUrl: `${localhostUrl}/Common/Upload`,
      loadingSubmit: false,
      id: null,
      // 表单数据
      formData: {
        longitude: '', // 经度
        latitude: '', // 纬度
        name: '', // 工点名称
        backedImageName: '', // 隧道示意图
        useTemplate: true, // 是否使用模板
        templateName: '', // 模板名称
        typeName: '' // 隧道类型
      },
      formRules: {
        name: [
          { required: true, message: '请输入工点名称', trigger: 'blur' },
          {
            validator: eleValidator([{ rule: 'isEmpty', msg: '工点名称不能为空' }]),
            trigger: 'blur'
          }
        ],
        longitude: [
          { required: true, message: '经度不能为空', trigger: 'blur' },
          {
            validator: eleValidator([
              { rule: 'isEmpty', msg: '经度不能为空' },
              { rule: 'isSpot', msg: '格式错误' },
              { rule: 'isIp', msg: '只能输入数字' }
            ]),
            trigger: 'change'
          }
        ],
        latitude: [
          { required: true, message: '纬度不能为空', trigger: 'blur' },
          {
            validator: eleValidator([
              { rule: 'isEmpty', msg: '纬度不能为空' },
              { rule: 'isSpot', msg: '格式错误' },
              { rule: 'isIp', msg: '只能输入数字' }
            ]),
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    'formData.templateName': function (newValue, oldValue) {
      this.formData.typeName = newValue
      if (newValue === '单洞') {
        this.formData.backedImageName = ''
        this.imgSrc = assetsImages.singleHole
      } else if (newValue === '双洞') {
        this.formData.backedImageName = ''
        this.imgSrc = assetsImages.doubleHole
      }
    },
    'formData.backedImageName': function (newValue, oldValue) {
      if (newValue) {
        this.imgSrc = this.imgUrl + newValue
        // 模板名称
        this.formData.templateName = ''
        // 是否使用模板
        this.formData.useTemplate = false
        // 隧道类型
        this.formData.typeName = '自定义'
      } else {
        // 是否使用模板
        this.formData.useTemplate = true
      }
    }
  },
  mounted() {
    this.getTunnelData()
  },
  methods: {
    // 上传成功
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.formData.backedImageName = res.data.url
        // 是否使用模板
        this.formData.useTemplate = false
        // 模板名称
        this.formData.templateName = ''
        // 隧道类型
        this.formData.typeName = '自定义'
      }
      this.$refs.imgRef.clearFiles()
    },
    // 上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
      return isJPG
    },
    // 保存
    handleSubmit() {
      this.$refs.RefForm.validate(async (flag) => {
        if (flag) {
          this.loadingSubmit = true
          let res
          try {
            if (this.isExist) {
              let obj = { id: this.id, value: this.formData }
              res = await tunnel('put', obj)
            } else {
              res = await tunnel('post', this.formData)
              this.getTunnelData()
            }
            if (res.code === 201) {
              this.$message.success('保存成功！')
            } else {
              this.$message.success('编辑成功！')
            }
            this.loadingSubmit = false
          } catch (err) {
            this.loadingSubmit = false
          }
        }
      })
    },
    // 获取数据
    async getTunnelData() {
      try {
        let { data } = await tunnel('get', null)
        this.isExist = true
        this.id = data.id
        this.formData = {
          longitude: data.longitude, // 经度
          latitude: data.latitude, // 纬度
          name: data.name, // 工点名称
          backedImageName: data.useTemplate ? '' : data.backedImageName, // 隧道示意图
          useTemplate: data.useTemplate, // 是否使用模板
          templateName: data.templateName, // 模板名称
          typeName: data.typeName // 隧道类型
        }
        this.formData.templateName = data.templateName
      } catch (err) {
        if (err.response.status === 404) {
          this.isExist = false
        }
      }
    }
    // async delRowReq(row) {
    //   try {
    //     if (!this.formData.useTemplate) { return }
    //     this.imgSrc = ''
    //     this.formData.backedImageName = ''
    //     this.formData.useTemplate = true
    //     this.formData.templateName = '单洞'
    //   } catch (err) {
    //     row.loadingDel = false
    //   }
    // },
    // handleRowDel(row) {
    //   row.loadingDel = true
    //   this.$_delConfirm('施工示意图', () => {
    //     this.delRowReq(row)
    //   }, () => {
    //     row.loadingDel = false
    //   })
    // }
  }
}
</script>

<style lang="scss" scoped>
  .imgBox {
    width: 1200px;
    height: 617px;
    margin: 0 auto;
    // overflow: hidden;
    position: relative;
    border: 1px solid #ccc;
    background-color: #ccc;
    .btnClass {
      position: absolute;
      right: 0;
      top: -30px;
    }
    img {
      width: 100%;
      height: 100%;
      float: left;
    }
  }
  .dialog-footer {
    width: 100%;
    display: flex;
    margin-top: 20px;
    margin-left: 105px;
    margin-bottom: 15px;
    justify-content: left;
  }
  .info {
    display: block;
    color: red;
  }
</style>
